<template>
  <div class="daas-cascader">
    <a-spin :spinning="loading">
      <a-popover
        v-model="visibled"
        overlay-class-name="daas-cascader-popover"
        :placement="placement"
        trigger="click"
        @visibleChange="handleVisible"
      >
        <div
          :class="
            `daas-cascader__input ${
              visibled ? 'border-color-show' : ''
            } daas-cascader__text__${size}`
          "
          @click="e => e.preventDefault()"
        >
          <div class="daas-cascader__input__content">
            <span
              :class="`text ${text ? '' : 'palaceholder'}`"
              :title="text || palaceholder"
              >{{ text || palaceholder }}</span
            >
          </div>
          <!-- <img
            :class="`icon ${visibled ? 'show' : 'hide'}`"
            src="@/static/img/select_down.svg"
          /> -->
          <a-icon type="down" />
        </div>
        <div slot="content" class="daas-cascader_content">
          <CascaderMenu
            :width="menuWidth"
            :options="data"
            :value="value"
            :title="title"
            :visibled="visibled"
            :height="menuHeight"
            :headers="headers"
            :indexed="indexed"
            :cascader-name="cascaderName"
            @close="handleClose"
            @reset="handleReset"
            @confirm="handleConfirm"
          />
        </div>
      </a-popover>
    </a-spin>
  </div>
</template>
<script>
import _ from "lodash";
import CascaderMenu from "./CascaderMenu.vue";
import {
  initSelect,
  initParentIndet,
  getMaxDeepValues,
  getLevelOptionsByValues,
  getSelectOptions
} from "@/utils/helper";

export default {
  name: "DaasCascader",
  components: {
    CascaderMenu
  },
  /**
   * events: 事件
   *  注意：使用组件必须定义change事件，并将返回的values更新到传入组件的value
   *   values: 选中项的key集合
   *   list: 选中项的数据集合
   *   values: 选中项的key按照层级划分
   *
   *  change: {
   *     type: Function
   *     default: (values, { values, list }) => ({})
   *  }
   */
  props: {
    // 数据源， 必填项
    data: {
      type: Array,
      default: () => []
    },
    // 选中项key， 必填项
    value: {
      type: Array,
      default: () => []
    },
    // 允许选择的key
    allowList: {
      type: Array,
      default: () => []
    },
    // 标题
    title: {
      type: String,
      default: "请选择"
    },
    // 弹框宽度
    menuWidth: {
      type: Number,
      default: 0
    },
    // 弹框内容body的宽度
    menuHeight: {
      type: Number,
      default: 324
    },
    // 是否需要索引
    indexed: {
      type: Boolean,
      default: false
    },
    // 加载状态
    loading: {
      type: Boolean,
      default: false
    },
    // 每列数据分类， 必填项
    headers: {
      type: Array,
      default: () => []
    },
    // 选择框大小
    size: {
      type: String,
      default: "default"
    },
    // 弹出框位置
    placement: {
      type: String,
      default: "bottomLeft"
    },
    // 选择框默认展示text
    palaceholder: {
      type: String,
      default: "全部"
    },
    // 级联选择框名称，用于区分多个级联框时，锚点问题， 必填项
    cascaderName: {
      type: String,
  
  default: "cascader"
    }
  },
  data() {
    return {
      icons: {},
      options: [],
      visibled: false,
      text: "",
      allowLists: []
    };
  },
  watch: {
    data(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.getNewAllowList();
        this.init(this.value);
      }
    },
    value(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.init(this.value);
      }
    },
    allowList(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.getNewAllowList();
        this.init(this.value);
      }
    }
  },
  mounted() {
    this.init(this.value);
  },
  methods: {
    init(values, type) {
      if (!this.data || !this.data.length) return;
      this.setLastSelected(values);
      this.setParentSelected(values);
      if (type && type === "reset") return;
      this.getText();
    },
    getNewAllowList() {
      if (!this.data || !this.data.length) return;
      this.allowLists = [];
      let list = getLevelOptionsByValues(this.data, this.allowList).filter(
        item => item.length
      );
      list = list && list.length ? list[list.length - 1] : [];
      if (list && list.length) {
        const allowLists = getMaxDeepValues(list, []);
        this.allowLists = _.uniq([...allowLists, ...this.allowList]);
      }
    },
    // 设置最内层的选中状态
    setLastSelected(values) {
      const selectedSet = new Set(values);
      const allowSet = new Set(this.allowLists);
      initSelect(this, this.data, selectedSet, allowSet);
    },
    // 设置父级的选中状态
    setParentSelected(values) {
      const selectedSet = new Set(values);
      const allowSet = new Set(this.allowLists);
      initParentIndet(this, this.data, selectedSet, allowSet);
    },
    handleClose() {
      this.visibled = false;
      this.init(this.value);
    },
    handleVisible(visibled) {
      if (!visibled) {
        this.init(this.value);
      }
    },
    getText() {
      let list = getSelectOptions(this.data).filter(item => item.length);
      if (list.length) {
        const length = list.length;
        const select = list[length - 1];
        this.text =
          select.length && select.length
            ? `已选${select.length}个${this.headers[length - 1]}`
            : "";
      } else {
        this.text = "";
      }
    },
    // 重置
    handleReset() {
      this.init([], "reset");
    },
    // 确定
    handleConfirm(values, selectedOptions, levelValues) {
      this.$emit("change", values, {
        values: levelValues,
        list: selectedOptions
      });
      this.visibled = false;
    }
  }
};
</script>
<style lang="less" scoped>
@primary-color: "#4dfecf";
@B: daas-cascader;
.@{B} {
  display: inline-block;
  width: 180px;
  background: #ffffff;

  &__input {
    min-width: 180px;
    display: flex;
    align-items: center;
    border: 1px solid #cdd0d7;
    padding: 0 12px;
    color: #2e3341;
    cursor: pointer;

    &:hover {
      border-color: @primary-color;
      transition: border-color 200ms;
    }

    &__content {
      flex: 1;
      display: flex;
      align-items: center;
      overflow: hidden;
      .text {
        width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .palaceholder {
        color: #cdd0d7;
      }
    }

    .show {
      transform: rotate(180deg);
    }
    .hide {
      transform: rotate(0deg);
    }

    .icon {
      width: 16px;
      flex: 0 0 auto;
      margin-left: 8px;
      transition: transform 200ms;
    }
  }

  .border-color-show {
    border-color: @primary-color;
  }

  &__text__large {
    font-size: 16px;
    height: 40px;
    line-height: 40px;
  }

  &__text__default {
    font-size: 14px;
    height: 32px;
    line-height: 32px;
  }

  &__text__small {
    font-size: 12px;
    height: 28px;
    line-height: 28px;
  }
}
</style>

<style lang="less">
.daas-cascader-popover {
  padding-top: 0 !important;
  z-index: 20000 !important;
  .ant-popover-arrow {
    display: none;
  }
  .ant-popover-inner-content {
    padding: 0;
  }
}
</style>
